package com.github.icloudpay.pay.core.util;
import java.util.List;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author jing.huang
 * @function
 * @date 2018年1月10日
 * @version 
 */
public class AESUtil {
    /** 
     * 密钥算法 
     */  
    private static final String ALGORITHM = "AES";  
    /** 
     * 加解密算法/工作模式/填充方式 
     */  
    private static final String ALGORITHM_MODE_PADDING = "AES/ECB/PKCS5Padding";  
  
    /** 
     * AES加密 
     *  
     * @param data 
     * @return 
     * @throws Exception 
     */  
    public static String encryptData(String data, String md5key) throws Exception {  
        // 创建密码器  
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);  
        // 初始化  
        SecretKeySpec key = new SecretKeySpec(WxMD5.MD5Encode(md5key).toLowerCase().getBytes(), ALGORITHM);  
        cipher.init(Cipher.ENCRYPT_MODE, key);  
        return Base64Util.encode(cipher.doFinal(data.getBytes()));  
    }  
  
    /** 
     * AES解密 
     *  
     * @param base64Data 
     * @return 
     * @throws Exception 
     */  
    public static String decryptData(String base64Data, String md5key) throws Exception {  
        Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING); 
        SecretKeySpec key = new SecretKeySpec(WxMD5.MD5Encode(md5key).toLowerCase().getBytes(), ALGORITHM);  
        cipher.init(Cipher.DECRYPT_MODE, key);  
        return new String(cipher.doFinal(Base64Util.decode(base64Data)));  
    }  
    
    /**
     * xml转json
     *
     * @param element
     * @param json
     */
    public static void dom4j2Json(Element element, JSONObject json) {
        // 如果是属性
        for (Object o : element.attributes()) {
            Attribute attr = (Attribute) o;
            if (!StringUtils.isEmpty(attr.getValue())) {
                json.put("@" + attr.getName(), attr.getValue());
            }
        }
        List<Element> chdEl = element.elements();
        if (chdEl.isEmpty() && !StringUtils.isEmpty(element.getText())) {// 如果没有子元素,只有一个值
            json.put(element.getName(), element.getText());
        }
 
        for (Element e : chdEl) {// 有子元素
            if (!e.elements().isEmpty()) {// 子元素也有子元素
                JSONObject chdjson = new JSONObject();
                dom4j2Json(e, chdjson);
                Object o = json.get(e.getName());
                if (o != null) {
                    JSONArray jsona = null;
                    if (o instanceof JSONObject) {// 如果此元素已存在,则转为jsonArray
                        JSONObject jsono = (JSONObject) o;
                        json.remove(e.getName());
                        jsona = new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if (o instanceof JSONArray) {
                        jsona = (JSONArray) o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                } else {
                    if (!chdjson.isEmpty()) {
                        json.put(e.getName(), chdjson);
                    }
                }
 
            } else {// 子元素没有子元素
                for (Object o : element.attributes()) {
                    Attribute attr = (Attribute) o;
                    if (!StringUtils.isEmpty(attr.getValue())) {
                        json.put("@" + attr.getName(), attr.getValue());
                    }
                }
                if (!e.getText().isEmpty()) {
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }
  
    public static void main(String[] args) throws Exception {  
        //解密
        String req_info = "Zg9L1jmxkqCnn4g3VKqXMpeDvCAvHTO5K3IN62K0t2y+Ox0SoB3u8vBzybhpmwKtOJP8jTFyO7950OXECD+3FlrdA4lxI94cSKr3RwU8iUHjxKhQA9DdWssx8FuH8TeDVwIbUCVvQZOEIf3hLs6RSOyceenZLfGy7FX3e9iT5ExatH74htVPh21ENEDpqwHqFxOn4g3NzY9ywkMMfnkqqfMj6ogEP3ZwmyX43fct+1YMnJonJKTC6dZFXuCOOhe9qdhKihOigBqqo1nDpO8gSNppfWl1+nLCPT+AOXpSlL3N+9unwBhVE0dX5eMyDxv53F1zqzxs5eetYePt+3t6t/BL8niHxu+kt4HXTlzQr5UgZatJA/SbMS7ycgAde36072XzFx/CSh/FHEWiY81ssRBtg3S8xaJBy+SLcsHCaLmCuAEEl3CeElIoPo1gVnLXitSX5CAgOzZbDlqY/7Ew2ge6GwobG6/PQk1LjeMQO5KeIPJY1fgH9ihrmH+yNlhDlg7BEWTqdcUF+F5wXfP6tR1zv8Jz/B/6k/bED5lM5h9nqyYGwVnwos52VTI+L1NYqfecux10ADoGwMgcej4FNeeqkwnEoSoto7jovU6sV//MZD/0Eaa7zKrJRiM3vbu4+BacXp2MxsC9QG0TBvDF2gfZx7Z6SGl1tyfMjwRvqBfU0BJ+MFmNpazPtz7PwHMUf1WIRGyjdaHdpx+K6muh2XiKGZeoy+MwlZ0uIEg88AHoxOryGbcOsmVhBnovrwrBHvm62kIYmVsM8kijEgpe1yynbex4Lh9rMDmmt6f4ct+TgGRJrcpfuurwcEOuRenlbTqFAX8YqfowuVXORgaXEsdIUGFZ4Rd4ytxJrIFJ/Y8A1KdJPsNc3vsx56gYB6VXo9e79nBrbz9ksSPeKMmHN6LX6DPBKjNbsAW2AriMPqDAPcLC4l+q4/IWYIJsSUMPXOPpNTF7SIXbNReIqmM+c+KGVUnZ1gUy4HHaQmyPO+kbF08So6uD6Vo71WNYIh0bpHoqy1PPIjkxYLQnd+tTbG6m5D/qvN9mCdSkDJBBAhM=";
        String md5key = "4b95cf4bddcb29d4941ab1e6c5b3fa77";
        String B = AESUtil.decryptData(req_info, md5key);
        System.out.println(B);
        Document doc;
        doc = DocumentHelper.parseText(B);
        JSONObject jsonPayOrderObject = new JSONObject();
        dom4j2Json(doc.getRootElement(), jsonPayOrderObject);
        System.out.println(jsonPayOrderObject.toJSONString());
    }
    
}
